<template>
  <div>
    <div
      class="header"
      v-if="showHeader"
    >
      <div
        class="header-content"
        :style="{ width: proxy.globalInfo.bodyWidth + 'px' }"
      >
        <!-- logo -->
        <router-link
          to="/"
          class="logo a-link"
        >
          <span
            v-for="item in logoInfo"
            :key="item.id"
            :style="{ color: item.color }"
          >{{ item.letter
            }}</span>
        </router-link>
        <!-- 板块信息 -->
        <div class="menu-panel">
          <router-link
            :class="['board-item home', activePBoardId == undefined ? 'active' : '']"
            to="/"
          >
            首页</router-link>
          <template
            v-for="board in boardList"
            :key="board.id"
          >
            <el-popover
              placement="bottom-start"
              :width="300"
              trigger="hover"
              v-if="board.children.length > 0"
            >
              <template #reference>
                <span
                  :class="['board-item', board.boardId == activePBoardId ? 'active' : '']"
                  @click="boardClickHandler(board)"
                >{{ board.boardName }}</span>
              </template>
              <div class="sub-board-list">
                <span
                  :class="['sub-board', subBoard.boardId == activeBoardId ? 'active' : '']"
                  @click="subBoardClickHandler(subBoard)"
                  v-for="subBoard in board.children"
                  :key="subBoard.id"
                >{{
                  subBoard.boardName }}</span>
              </div>
            </el-popover>
            <span
              :class="['board-item', board.boardId == activePBoardId ? 'active' : '']"
              v-else
              @click="boardClickHandler(board)"
            >{{ board.boardName }}</span>
          </template>
        </div>
        <!-- 用户信息 -->
        <div class="userInfo-panel">
          <el-button
            class="op-btn"
            type="primary"
            @click="newPost"
          >发帖 <span class="iconfont icon-add"></span></el-button>
          <el-button
            class="op-btnSearch"
            type="primary"
            @click="goSearch"
          >搜索 <span class="iconfont icon-search"></span></el-button>
          <template v-if="userInfo.userId">
            <div class="message-info">
              <el-dropdown>
                <el-badge
                  :value="messageCountInfo.total"
                  class="item"
                  :hidden="messageCountInfo.total == null || messageCountInfo.total == 0"
                >
                  <div class="iconfont icon-message"></div>
                </el-badge>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item
                      class="message-item"
                      @click="goToMessage('reply')"
                    ><span class="text">回复我的</span><span
                        class="count-tag"
                        v-if="messageCountInfo.reply > 0"
                      >{{ messageCountInfo.reply > 99 ? '99+' :
                        messageCountInfo.reply
                        }}</span></el-dropdown-item>
                    <el-dropdown-item
                      class="message-item"
                      @click="goToMessage('likePost')"
                    ><span class="text">赞了我的文章</span><span
                        class="count-tag"
                        v-if="messageCountInfo.likePost > 0"
                      >{{ messageCountInfo.likePost > 99 ? '99+' :
                        messageCountInfo.likePost
                        }}</span></el-dropdown-item>
                    <el-dropdown-item
                      class="message-item"
                      @click="goToMessage('downloadAttachment')"
                    ><span class="text">下载了我的附件</span><span
                        class="count-tag"
                        v-if="messageCountInfo.downloadAttachment > 0"
                      >{{ messageCountInfo.downloadAttachment >
                        99 ? '99+' :
                        messageCountInfo.downloadAttachment
                        }}</span></el-dropdown-item>
                    <el-dropdown-item
                      class="message-item"
                      @click="goToMessage('likeComment')"
                    ><span class="text">赞了我的评论</span><span
                        class="count-tag"
                        v-if="messageCountInfo.likeComment > 0"
                      >{{ messageCountInfo.likeComment > 99 ?
                        '99+' :
                        messageCountInfo.likeComment
                        }}</span></el-dropdown-item>
                    <el-dropdown-item
                      class="message-item"
                      @click="goToMessage('sys')"
                    ><span class="text">系统消息</span><span
                        class="count-tag"
                        v-if="messageCountInfo.sys > 0"
                      >{{ messageCountInfo.sys > 99 ? '99+' :
                        messageCountInfo.sys
                      }}</span></el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
            <div class="user-info">
              <el-dropdown>
                <Avatar
                  :userId="userInfo.userId"
                  :width="50"
                  :addLink="false"
                ></Avatar>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="goToUcenter(userInfo.userId)">我的主页</el-dropdown-item>
                    <el-dropdown-item @click="logout">退出</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
          <!-- 登录，注册 用户信息 -->
          <el-button-group
            style="margin-left: 10px;"
            v-else
          >
            <el-button
              type="primary"
              size="default"
              @click="loginAndReg(1)"
              plain
            >登录</el-button>
            <el-button
              type="primary"
              size="default"
              @click="loginAndReg(0)"
              plain
            >注册</el-button>
          </el-button-group>
        </div>
      </div>
    </div>
    <div class="body-content">
      <router-view />
    </div>
    <!-- 底部 -->
    <div
      class="footer"
      v-if="showFooter"
    >
      <div
        class="foot-content"
        :style="{ width: proxy.globalInfo.bodyWidth + 'px' }"
      >
        <!-- logo -->
        <el-row>
          <el-col
            :span="6"
            class="item"
          >
            <div class="logo">
              <div class="logo-letter">
                <span
                  v-for="item in logoInfo"
                  :key="item.id"
                  :style="{ color: item.color }"
                >{{ item.letter
                }}</span>
              </div>
              <div class="info">一个可供交流的社区</div>
            </div>
          </el-col>
          <el-col
            :span="6"
            class="item"
          >
            <div class="title">网站相关</div>
            <div>
              <div
                class="item-a"
                style="margin: 8px 0px;"
              >
                <a
                  href="/post/vpNQ0Yp7KxqPU1w"
                  class="a-link"
                >常见问题</a>
              </div>
              <div
                class="item-a"
                style="margin: 8px 0px;"
              >
                <a
                  href="/post/njNJ6tnItAm1i28"
                  class="a-link"
                >规章制度</a>
              </div>
              <div
                class="item-a"
                style="margin: 8px 0px;"
              >
                <a
                  href="/post/5QbW8pVDvTg9gLa"
                  class="a-link"
                >免责声明</a>
              </div>
            </div>
          </el-col>
          <el-col
            :span="6"
            class="item"
          >
            <div class="title">友情链接</div>
            <div>
              <div>
                <a
                  href="
                #"
                  class="a-link"
                >语堂</a>
              </div>
            </div>
          </el-col>
          <el-col
            :span="6"
            class="item"
          >
            <div class="title">关注站长</div>
            <div>
              <img
                class="footer-img"
                style="width: 90px;"
                src="../assets/touch.jpg"
                alt=""
              >
            </div>
          </el-col>
          <el-col
            :span="6"
            class="item"
          >

          </el-col>

        </el-row>

      </div>
    </div>
    <!-- 登录注册 -->
    <LogAndReg ref="loginRegisterRef"></LogAndReg>
    <!-- 回到顶部 -->
    <el-backtop
      :right="100"
      :bottom="100"
    ></el-backtop>

  </div>
</template>

<script setup>
import LogAndReg from './LogAndReg.vue';
import { onMounted, watch } from 'vue';
import { ref, reactive, getCurrentInstance, nextTick } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { useStore } from 'vuex';
const { proxy } = getCurrentInstance();
const route = useRoute();
const router = useRouter();
const store = useStore()

const api = {
  getUserInfo: '/getUserInfo',
  loadBoard: '/board/loadBoard',
  loadMessageCount: '/ucenter/getMessageCount',
  logout: '/logout',
  loadSetting: '/getSysSetting'
}

onMounted(() => {
  initScroll();
  getUserInfo();
  loadSetting();
})

// 获取用户登录信息
const getUserInfo = async () => {
  let result = await proxy.Request({
    url: api.getUserInfo
  });
  if (!result) {
    return
  };
  store.commit("updateLoginUserInfo", result.data)
}

// 获取板块信息
const boardList = ref([]);
const loadBoard = async () => {
  let result = await proxy.Request({
    url: api.loadBoard
  });
  if (!result) {
    return
  }
  boardList.value = result.data
  store.commit("saveBoardList", boardList.value)
}
loadBoard();

// 监听用户信息
const userInfo = ref({})
watch(
  () => store.state.loginUserInfo,
  (newVal, oldVal) => {
    if (newVal != undefined && newVal != null) {
      userInfo.value = newVal
    } else {
      userInfo.value = {}
    }
  },
  { immediate: true, deep: true }
)

// 监听是否展示登录框
watch(
  () => store.state.showLogin,
  (newVal, oldVal) => {
    if (newVal) {
      loginAndReg(1);
    }
  }, { immediate: true, deep: true }
);

const logoInfo = ref([
  {
    letter: '语',
    color: '#FF6347'
  },
  {
    letter: '堂',
    color: '#FFA500'
  },
])

const showHeader = ref(true);

const getScrollTop = () => {
  let getScroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
  return getScroll;
}

const initScroll = () => {
  let initScrollTop = getScrollTop();
  let scrollType = 0;
  window.addEventListener("scroll", () => {
    let currentScrollTop = getScrollTop()
    if (currentScrollTop > initScrollTop) {
      // 向下滚动
      scrollType = 1;
    } else {
      // 向下滚动
      scrollType = 0;
    }
    initScrollTop = currentScrollTop;
    if (currentScrollTop > 230 && scrollType == 1) {
      showHeader.value = false
    } else {
      showHeader.value = true
    }
  })
}

// 登录注册
const loginRegisterRef = ref();
const loginAndReg = (type) => {
  loginRegisterRef.value.showPanel(type);
}

// 板块点击
// 一级板块
const boardClickHandler = (board) => {
  router.push(`/forum/${board.boardId}`)
}

// 二级板块
const subBoardClickHandler = (subBoard) => {
  router.push(`/forum/${subBoard.pBoardId}/${subBoard.boardId}`)
}

// 当前选中的板块
const activePBoardId = ref(0);
watch(() => store.state.activePBoardId,
  (newVal, oldVal) => {
    activePBoardId.value = newVal
  }, { immediate: true, deep: true });

const activeBoardId = ref(0);
watch(() => store.state.activeBoardId,
  (newVal, oldVal) => {
    activeBoardId.value = newVal
  }, { immediate: true, deep: true });

// 发帖
const newPost = () => {
  if (!userInfo.value.userId) {
    loginAndReg(1);
    return;
  }
  router.push('/newPost')
}

// 个人主页
const goToUcenter = (userId) => {
  router.push(`/user/${userId}`)
}

// 我的消息中心
const goToMessage = (type) => {
  router.push(`/user/message/${type}`)
}

const messageCountInfo = ref({});
const loadMessageCount = async () => {
  let result = await proxy.Request({
    url: api.loadMessageCount,
  })
  if (!result) {
    return;
  }
  messageCountInfo.value = result.data
  store.commit('updateMessageCountInfo', result.data)
}

// 动态保存消息信息数量
watch(() => store.state.messageCountInfo, (newVal, oldVal) => {
  messageCountInfo.value = newVal
}, { immediate: true, deep: true })

// 在检测到用户登录时随时监听 进行消息提示
watch(() => store.state.loginUserInfo, (newVal, oldVal) => {
  if (newVal) {
    loadMessageCount();
  }
}, { immediate: true, deep: true });

const logout = () => {
  proxy.Confirm('确定要退出吗', async () => {
    let result = await proxy.Request({
      url: api.logout,
    })
    if (!result) {
      return;
    }
    store.commit('updateLoginUserInfo', null)
  })
}

// 获取系统配置
const loadSetting = async () => {
  let result = await proxy.Request({
    url: api.loadSetting,
  })
  if (!result) {
    return;
  }
  store.commit('saveSysSetting', result.data)
}

const goSearch = () => {
  router.push('/search')
}

const showFooter = ref(true)
watch(() => route.path, (newVal, oldVal) => {
  if (newVal.includes("newPost") || newVal.includes("editPost")) {
    showFooter.value = false
  } else {
    showFooter.value = true
  }
  console.log(newVal, showFooter.value);

}, { immediate: true, deep: true });
</script>

<style lang="scss">
.header {
  top: 0;
  width: 100%;
  position: fixed;
  box-shadow: 0 2px 6px 0 #ddd;
  z-index: 1000;
  background: #fff;

  .header-content {
    margin: 0 auto;
    height: 70px;
    display: flex;
    align-items: center;

    .logo {
      display: block;
      margin-right: 10px;
      font-size: 30px;
    }

    .menu-panel {
      flex: 1;

      .board-item {
        margin-left: 10px;
        cursor: pointer;
      }

      .board-item:hover {
        color: var(--link);

      }

      .home {
        text-decoration: none;
        color: #636d7e;
      }

      .active {
        color: var(--link);
      }
    }

    .userInfo-panel {
      width: 300px;
      display: flex;
      align-items: center;

      .op-btnSearch {
        margin-left: 7px;
      }

      .message-info {
        margin-left: 5px;
        margin-right: 25px;
        cursor: pointer;

        .icon-message {
          font-size: 25px;
          color: rgb(147, 147, 147);
          cursor: pointer;
        }


      }

      .user-info {
        margin-left: 15px;
        cursor: pointer;
      }
    }
  }
}

.sub-board-list {
  display: flex;
  flex-wrap: wrap;

  .sub-board {
    padding: 0px 10px;
    border-radius: 20px;
    margin-right: 10px;
    background: #fffdfd;
    border: 1px solid #828282;
    color: #909090;
    margin-top: 10px;
    cursor: pointer;
  }



  .sub-board:hover {
    color: var(--link);
  }

  .active {
    background: var(--link);
    color: #fff;
  }

  .active:hover {
    color: #fff;
  }
}

.body-content {
  margin-top: 75px;
  position: relative;
  min-height: calc(100vh - 225px);
}

.message-item {
  display: flex;
  justify-content: space-around;

  .text {
    flex: 1;
  }

  .count-tag {
    width: 25px;
    height: 20px;
    display: block;
    background: #f56c6c;
    border-radius: 50%;
    font-size: 13px;
    text-align: center;
    color: #fff;
    margin-left: 10px;
  }
}

.el-badge__content.is-fixed {
  right: calc(1px + var(--el-badge-size) / 2) !important;
  top: 0 !important;
}

.footer {
  background: #e9e9e9;
  height: 140px;
  margin-top: 10px;

  .foot-content {
    margin: 0 auto;
    padding-top: 10px;

    .item {
      .title {
        font-size: 18px;
        margin-bottom: 10px;

        .a-link {
          line-height: 25px;
          font-size: 14px;
          color: var(--text2);
        }

        .footer-img {
          width: 100%;
          height: 100%;
          object-fit: cover;

        }
      }

      .logo {
        .logo-letter {
          font-size: 30px;
          margin-bottom: 10px;
        }

        .info {
          color: #636d7e;
        }
      }
    }
  }
}
</style>
